<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
    use HasFactory;
    use HasDateTimeFormatter;
    use ModelTree;

    protected $depthColumn = 'depth';
    protected $fillable = [
        'parent_id',
        'order',
        'title',
        'depth',
    ];

    public function users(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Administrator::class, 'user_has_department', 'department_id', 'user_id');
    }

    public function children()
    {
        return $this->hasMany(self::class, 'parent_id');
    }

    public function grandchildren()
    {
        return $this->children()->with('grandchildren');
    }

    public function grandchildrenUsers()
    {
        return $this->children()->with(['grandchildrenUsers' => function ($q) {
            $q->select(['id', 'parent_id'])->with(['users' => function ($query) {
                $query->select(['id']);
            }]);
        }]);
    }

    public static function parserDescendantsAndSelfId($data): \Illuminate\Support\Collection
    {
        $result = collect();
        foreach ($data as $item) {
            $result->push($item['id']);
            if ($item->grandchildren && count($item->grandchildren))
                $result = self::parserDescendantsAndSelfId($item->grandchildren)->merge($result);
        }
        return $result;
    }

    public static function descendantsAndSelfId($query): \Illuminate\Support\Collection
    {
        $departments = $query
            ->select(['id', 'parent_id' ,'title'])
            ->with(['grandchildren' => function ($query) {
                $query->select(['id', 'parent_id' ,'title']);
            }])
            ->get();
//        dd($departments->toArray());
        return self::parserDescendantsAndSelfId($departments);
    }

    /**
     * Get options for Select field in form.
     *
     * @param \Closure|null $closure
     * @param null $rootText
     * @param bool $displayRoot
     * @return array
     */
    public static function selectOptions(\Closure $closure = null, $rootText = null, bool $displayRoot = true): array
    {

        $options = (new static())->withQuery($closure)->buildSelectOptions();
        $r = collect($options);
        if ($displayRoot) {
            $rootText = $rootText ?: admin_trans_label('root');
            $r = $r->prepend($rootText, 0);
        }
        return $r->all();
    }

}
